package com.hyphenate.easeui.widget.chatrow;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.google.gson.Gson;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chatuidemo.DemoApplication;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.exceptions.HyphenateException;
import com.joplus.housekeeper.R;
import com.joplus.housekeeper.bean.ChatCard;
import com.joplus.housekeeper.core.OrderStatus;
import com.joplus.housekeeper.network.RequestHelper;
import com.joplus.housekeeper.network.TextCallback;

import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


/**
 * 储值卡卡片
 */
public class EaseChatRowText_Buy extends EaseChatRow {

    private TextView contentView;

    private LinearLayout layoutCard, layoutCardList;
    private TextView tvCardSubject, tvCardPay;


    private String rewarId;
    private String isClick;


    public EaseChatRowText_Buy(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);

    }

    @Override
    protected void onInflatView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                R.layout.ease_row_received_message_hermes : R.layout.ease_row_sent_message, this);

    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(R.id.tv_chatcontent);
        //card
        layoutCard = (LinearLayout) findViewById(R.id.layout_card);
        layoutCardList = (LinearLayout) findViewById(R.id.layout_card_list);
        tvCardSubject = (TextView) findViewById(R.id.tv_card_subject);
        tvCardPay = (TextView) findViewById(R.id.tv_card_pay);


    }

    @Override
    public void onSetUpView() {
        /*if (message.getBody()!=null){*/
        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
        Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
        // 设置内容
        contentView.setText(span, BufferType.SPANNABLE);


        String msg = txtBody.getMessage();
//        if(msg.contains("&quot;")){
//            msg.replace("&quot;","\"\"");
//        }
        try {
            new JSONObject(msg);
            Gson gson = new Gson();
            ChatCard chatCard = gson.fromJson(txtBody.getMessage(), ChatCard.class);
            bubbleLayout.setVisibility(View.GONE);
            layoutCardList.removeAllViews();
            contentView.setVisibility(View.GONE);
            String subject = chatCard.getSubject();
            setCard(chatCard);
        } catch (Exception e) {

            bubbleLayout.setVisibility(View.VISIBLE);
            layoutCard.setVisibility(View.GONE);

            contentView.setVisibility(View.VISIBLE);

        }
//        handleTextMessage();

    }

    private void setCard(ChatCard chatCard) {
        tvCardSubject.setText(chatCard.getSubject());
        List<ChatCard.CardInfoBean> cardInfoBeanList = chatCard.getCardInfo();
        for (ChatCard.CardInfoBean cardInfoBean :
                cardInfoBeanList) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_card_list, null);
            TextView tvKey = (TextView) view.findViewById(R.id.tv_card_list_key);
            TextView tvValue = (TextView) view.findViewById(R.id.tv_card_list_value);

            tvKey.setText(cardInfoBean.getKey());
            tvValue.setText(cardInfoBean.getValue());
            layoutCardList.addView(view);
        }

        try {
            JSONObject jsonObject = message.getJSONObjectAttribute("orderStatus");
            setOrderStatus(jsonObject.toString(), chatCard);
            orderStatus(chatCard);
            L.e("本地有该条订单状态: " + jsonObject.toString());
        } catch (HyphenateException e) {
            e.printStackTrace();
            L.e("本地无该条订单状态: " + e.toString());
            orderStatus(chatCard);
        }

    }


    private void orderStatus(final ChatCard chatCard) {
        RequestHelper.getInstance().orderStatus(context, chatCard.getOrderId(),
                new TextCallback() {
                    @Override
                    public void onSuccess(Object info) {

                        setOrderStatus((String) info, chatCard);

                    }

                    @Override
                    public void onFailure(String error) {


                    }
                });
    }

    private void setOrderStatus(String info, final ChatCard chatCard) {
        String txtStatus = "";

        JSONObject jsonObject = null;
        L.e("ChatCard" + " " + chatCard.toString());
        try {
            final String orderInfo = info;
            jsonObject = new JSONObject(orderInfo);
            final String orderStatus = jsonObject.getJSONObject("data").getString("orderStatus");


            L.e("EaseChatRowText-->" + "orderInfo-->" + orderInfo);
            switch (OrderStatus.getOrderType(orderStatus)) {
                case WAIT_PAY:
                    txtStatus = chatCard.getOrderMoney() + "元 去支付";
                    tvCardPay.setBackgroundColor(getResources().getColor(R.color.jo_shop_detial_line));
                    break;
                case HAD_PAY:
                    txtStatus = "已支付";
                    message.setAttribute("orderStatus", jsonObject);
                    if (chatCard.getCardInfo().size() <= 0) {
                        txtStatus = "已支付";
                        message.setAttribute("orderStatus", jsonObject);
                    }
                    tvCardPay.setBackgroundColor(Color.GRAY);
                    break;
                case FINISH:
                case CANCEL:
                case DISABLE:
                case REFUNDING:
                case REFUNDED:
                case REFUSE:
                    txtStatus = OrderStatus.getOrderType(orderStatus).getName();
                    message.setAttribute("orderStatus", jsonObject);
                    tvCardPay.setBackgroundColor(Color.GRAY);
                    break;


            }



            ;

        } catch (JSONException e) {


            tvCardPay.setBackgroundColor(Color.GRAY);
            try {
                String errorMsg = jsonObject.getString("errorMsg");
                message.setAttribute("orderStatus", jsonObject);
                txtStatus = errorMsg;

            } catch (JSONException e1) {

            }

        }
        if(!isMyCard(chatCard.getAccountId())){
            txtStatus="错误卡片";
        }
        StringUtils.setText(tvCardPay, txtStatus);


    }


//    protected void handleTextMessage() {
//        if (message.direct() == EMMessage.Direct.SEND) {
//            setMessageSendCallback();
//            switch (message.status()) {
//                case CREATE:
//                    progressBar.setVisibility(View.GONE);
//                    statusView.setVisibility(View.VISIBLE);
//                    // 发送消息
//                    //               sendMsgInBackground(message);
//                    break;
//                case SUCCESS: // 发送成功
//                    progressBar.setVisibility(View.GONE);
//                    statusView.setVisibility(View.GONE);
//                    break;
//                case FAIL: // 发送失败
//                    progressBar.setVisibility(View.GONE);
//                    statusView.setVisibility(View.VISIBLE);
//                    break;
//                case INPROGRESS: // 发送中
//                    progressBar.setVisibility(View.VISIBLE);
//                    statusView.setVisibility(View.GONE);
//                    break;
//                default:
//                    break;
//            }
//        } else {
//            if (!message.isAcked() && message.getChatType() == ChatType.Chat) {
//                try {
//                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
//                } catch (HyphenateException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
        L.e("点击了聊天文字");
    }


    /**
     * 判断是否是我自己的卡片，可能是后台发错了！
     * @return
     */
    private boolean isMyCard(String cardaccoundId){
        if(cardaccoundId!=null){
            return cardaccoundId.equals(DemoApplication.getInstance().getUser().getData().getAccountId());
        }
        return  true;
    }

}
